package com.easysettle

import android.Manifest
import android.content.Intent
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.budiyev.android.codescanner.AutoFocusMode
import com.budiyev.android.codescanner.CodeScanner
import com.budiyev.android.codescanner.CodeScannerView
import com.budiyev.android.codescanner.DecodeCallback
import com.budiyev.android.codescanner.ErrorCallback
import com.budiyev.android.codescanner.ScanMode
import com.easysettle.model.Product
import com.easysettle.service.MainService

/**
 * 快速识别Activity
 * 用于通过扫描条形码或手动输入商品ID快速识别商品
 */
class QuickScanActivity : AppCompatActivity() {
    // UI组件
    private lateinit var scannerView: CodeScannerView
    private lateinit var btnBack: Button
    private lateinit var btnManualInputId: Button
    private lateinit var productInfoContainer: View
    private lateinit var tvProductId: TextView
    private lateinit var tvProductName: TextView
    private lateinit var tvProductPrice: TextView
    private lateinit var tvProductBarcode: TextView
    private lateinit var btnAddToCart: Button
    private lateinit var btnBackToScan: Button
    
    // 主服务实例
    private lateinit var mainService: MainService
    // 条形码扫描器
    private lateinit var codeScanner: CodeScanner
    // 线程池，用于执行后台任务
    private val executorService = java.util.concurrent.Executors.newSingleThreadExecutor()

    companion object {
        // 日志标签
        private const val TAG = "QuickScanActivity"
        // 商品ID输入请求码
        private const val PRODUCT_ID_INPUT_REQUEST = 105
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_quick_scan)
        
        // 初始化UI组件
        scannerView = findViewById(R.id.scannerView)
        btnBack = findViewById(R.id.btn_back)
        btnManualInputId = findViewById(R.id.btn_manual_input_id)
        productInfoContainer = findViewById(R.id.product_info_container)
        tvProductId = findViewById(R.id.tv_product_id)
        tvProductName = findViewById(R.id.tv_product_name)
        tvProductPrice = findViewById(R.id.tv_product_price)
        tvProductBarcode = findViewById(R.id.tv_product_barcode)
        btnAddToCart = findViewById(R.id.btn_add_to_cart)
        btnBackToScan = findViewById(R.id.btn_back_to_scan)
        
        // 初始化主服务
        mainService = MainService(this)
        
        // 初始化条形码扫描器
        setupCodeScanner()
        
        // 设置返回按钮点击事件
        btnBack.setOnClickListener {
            finish()
        }
        
        // 设置手动输入商品ID按钮点击事件
        btnManualInputId.setOnClickListener {
            showManualIdInputDialog()
        }
        
        // 检查相机权限
        checkCameraPermission()
    }

    /**
     * 初始化条形码扫描器
     */
    private fun setupCodeScanner() {
        codeScanner = CodeScanner(this, scannerView)
        
        // 配置扫描器参数
        codeScanner.apply {
            camera = CodeScanner.CAMERA_BACK
            formats = CodeScanner.ALL_FORMATS // 支持所有条码格式
            autoFocusMode = AutoFocusMode.SAFE
            scanMode = ScanMode.SINGLE
            isAutoFocusEnabled = true
            isFlashEnabled = false
        }
        
        // 设置解码回调
        codeScanner.decodeCallback = DecodeCallback {
            runOnUiThread {
                // 隐藏扫描器，显示商品信息
                scannerView.visibility = View.GONE
                productInfoContainer.visibility = View.VISIBLE
                
                // 查找对应商品
                findProductByBarcode(it.text)
            }
        }
        
        // 设置错误回调
        codeScanner.errorCallback = object : ErrorCallback {
            override fun onError(error: Throwable) {
                runOnUiThread {
                    Toast.makeText(this@QuickScanActivity, "相机初始化错误: ${error.message}", Toast.LENGTH_LONG).show()
                }
            }
        }
        
        // 设置扫描器点击事件（重新启动扫描）
        scannerView.setOnClickListener {
            codeScanner.startPreview()
        }
    }

    /**
     * 检查相机权限
     */
    private fun checkCameraPermission() {
        if (!mainService.hasPermission(Manifest.permission.CAMERA)) {
            mainService.requestPermission(Manifest.permission.CAMERA, MainService.PERMISSION_CAMERA_REQUEST_CODE)
        } else {
            startScanner()
        }
    }

    /**
     * 启动扫描器
     */
    private fun startScanner() {
        codeScanner.startPreview()
    }

    /**
     * 通过条形码查找商品
     */
    private fun findProductByBarcode(barcode: String) {
        // 使用线程池执行后台查询
        executorService.execute {
            val product = mainService.getProductByBarcode(barcode)
            runOnUiThread {
                if (product != null) {
                    showProductInfo(product)
                } else {
                    showProductNotFound(barcode)
                }
            }
        }
    }

    /**
     * 通过ID查找商品
     */
    private fun findProductById(productId: String) {
        // 使用线程池执行后台查询
        executorService.execute {
            val products = mainService.searchProducts(productId)
            runOnUiThread {
                when {
                    products.isEmpty() -> {
                        showProductNotFound(productId)
                    }
                    products.size == 1 -> {
                        showProductInfo(products[0])
                    }
                    else -> {
                        showProductSelectionDialog(products)
                    }
                }
            }
        }
    }

    /**
     * 显示商品选择对话框
     */
    private fun showProductSelectionDialog(products: List<Product>) {
        val productNames = products.map { "${String.format("%03d", it.id.toIntOrNull() ?: 0)} - ${it.name} (¥${String.format("%.2f", it.price)})" }.toTypedArray()
        
        AlertDialog.Builder(this)
            .setTitle("选择商品")
            .setItems(productNames) { dialog, which ->
                val selectedProduct = products[which]
                showProductInfo(selectedProduct)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 显示商品信息
     */
    private fun showProductInfo(product: Product) {
        tvProductId.text = String.format("%03d", product.id.toIntOrNull() ?: 0)
        tvProductName.text = product.name
        tvProductPrice.text = String.format("¥%.2f", product.price)
        tvProductBarcode.text = if (product.barcode.isEmpty()) "未设置" else product.barcode
        
        // 设置添加到购物车按钮点击事件
        btnAddToCart.setOnClickListener {
            addToCart(product)
        }
        
        // 设置返回扫描按钮点击事件
        btnBackToScan.setOnClickListener {
            productInfoContainer.visibility = View.GONE
            scannerView.visibility = View.VISIBLE
            codeScanner.startPreview()
        }
    }

    /**
     * 显示商品未找到提示
     */
    private fun showProductNotFound(identifier: String) {
        tvProductId.text = "--"
        tvProductName.text = "未找到商品"
        tvProductPrice.text = "¥0.00"
        tvProductBarcode.text = identifier
        
        // 隐藏添加到购物车按钮
        btnAddToCart.visibility = View.GONE
        
        // 设置返回扫描按钮点击事件
        btnBackToScan.setOnClickListener {
            productInfoContainer.visibility = View.GONE
            scannerView.visibility = View.VISIBLE
            codeScanner.startPreview()
        }
    }

    /**
     * 将商品添加到购物车
     */
    private fun addToCart(product: Product) {
        mainService.addToCart(product) { success ->
            runOnUiThread {
                if (success) {
                    Toast.makeText(this@QuickScanActivity, "已添加到购物车", Toast.LENGTH_SHORT).show()
                    productInfoContainer.visibility = View.GONE
                    scannerView.visibility = View.VISIBLE
                    codeScanner.startPreview()
                } else {
                    Toast.makeText(this@QuickScanActivity, "添加到购物车失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 显示手动输入商品ID对话框
     */
    private fun showManualIdInputDialog() {
        val builder = AlertDialog.Builder(this)
        val inflater = layoutInflater
        val dialogView = inflater.inflate(R.layout.dialog_input_product_id, null)
        val etProductId = dialogView.findViewById<com.google.android.material.textfield.TextInputEditText>(R.id.et_product_id)
        
        builder.setView(dialogView)
            .setTitle("输入商品ID或名称")
            .setPositiveButton("确定") {
                dialog, which ->
                val query = etProductId.text.toString().trim()
                if (query.isNotEmpty()) {
                    // 隐藏扫描器，显示商品信息
                    scannerView.visibility = View.GONE
                    productInfoContainer.visibility = View.VISIBLE
                       
                    // 查找对应商品
                    findProductById(productId = query)
                } else {
                    Toast.makeText(this@QuickScanActivity, "请输入商品ID或名称", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        if (requestCode == MainService.PERMISSION_CAMERA_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                startScanner()
            } else {
                Toast.makeText(this, "需要相机权限才能扫描条形码", Toast.LENGTH_SHORT).show()
                finish()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (this::codeScanner.isInitialized) {
            codeScanner.startPreview()
        }
    }

    override fun onPause() {
        if (this::codeScanner.isInitialized) {
            codeScanner.releaseResources()
        }
        super.onPause()
    }
}